package com.hxzy.service.impl;

import com.hxzy.anno.OperateLog;
import com.hxzy.mapper.DeptMapper;
import com.hxzy.mapper.EmpMapper;
import com.hxzy.pojo.Dept;
import com.hxzy.pojo.DeptLog;
import com.hxzy.service.DeptLogService;
import com.hxzy.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author wzm
 * @create 2023-10-07 16:44
 * project_name:stu_sys
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    //根据id删除部门信息 同时删除部门下的所有员工
    @Override
    @OperateLog
    @Transactional(rollbackFor = Exception.class) //为当前方法添加事务操作
    public void delete(Integer id) throws Exception {

        try {
            //调用持久层进行删除
            deptMapper.deleteById(id);

            //出现错误 运行时异常
//            int i = 1 / 0;
            //模拟编译时异常
/*        if(true){
            throw new Exception();
        }*/

            //根据dept_id删除所有这个部门的员工
            empMapper.deleteByDeptId(id);
        }finally {
            //无论提交还是回滚都要执行插入日志的操作
            DeptLog deptLog = new DeptLog();
            //创建时间
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了删除部门操作，同时删除了部门的员工，此时删除的部门号为："+id);
            deptLogService.insert(deptLog);//不能受当期那事务的影响
        }

    }

    @Override
    @OperateLog
    public void add(Dept dept) {
        //对于字段的补充
        dept.setCreateTime(LocalDateTime.now());//创建时间
        dept.setUpdateTime(LocalDateTime.now());//修改时间
        //调用mapper层进行添加
        deptMapper.add(dept);
    }

    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }

    @Override
    @OperateLog
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
